package cn.stylefeng.guns.modular.recy.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.shiro.ShiroUser;
import cn.stylefeng.guns.modular.system.entity.Dict;
import cn.stylefeng.roses.core.base.controller.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
import me.chanjar.weixin.mp.api.*;
import cn.stylefeng.guns.modular.recy.service.*;
import cn.stylefeng.guns.core.common.page.*;
import com.baomidou.mybatisplus.core.metadata.*;
import com.baomidou.mybatisplus.core.conditions.*;
import cn.stylefeng.guns.modular.recy.vo.*;
import cn.hutool.core.bean.*;

import java.util.List;
import java.util.stream.*;
import cn.stylefeng.guns.modular.recy.warpper.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.*;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.*;
import cn.hutool.core.map.*;
import cn.stylefeng.guns.modular.miniapp.config.*;
import cn.stylefeng.guns.modular.weixin.utils.*;
import org.apache.commons.lang3.*;
import cn.stylefeng.roses.core.reqres.response.*;
import me.chanjar.weixin.common.error.*;
import cn.binarywang.wx.miniapp.api.*;
import cn.binarywang.wx.miniapp.bean.*;
import cn.hutool.core.date.*;
import cn.stylefeng.guns.modular.recy.vo.wx.*;
import cn.hutool.core.util.*;
import cn.stylefeng.guns.core.common.constant.*;
import cn.stylefeng.roses.core.util.*;
import me.chanjar.weixin.mp.bean.result.*;
import me.chanjar.weixin.common.bean.result.*;
import com.github.binarywang.utils.qrcode.*;
import java.util.*;
import org.apache.commons.io.*;
import java.io.*;
import javax.imageio.*;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.*;
import java.awt.*;
import com.baomidou.mybatisplus.core.conditions.query.*;
import cn.stylefeng.guns.modular.recy.entity.*;
import cn.stylefeng.guns.modular.recy.utils.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import java.lang.invoke.*;

@Controller
@RequestMapping({ "/wechatUser" })
public class WechatUserController extends BaseController
{
    private String PREFIX;
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private WxMpService wxService;
    @Autowired
    private UserNoCreator userNoCreator;

    @Autowired
    private WasteTypeService wasteTypeService;

    @Autowired
    private UserBinService userBinService;

    @Autowired
    private ProductService productService;

    @Autowired
    private RegionService regionService;
    @Autowired
    private WasteStationService wasteStationService;

    @Autowired
    private OrderFormService orderFormService;




    public WechatUserController() {
        this.PREFIX = "/modular/recy/wechatUser/";
    }
    
    @RequestMapping({ "" })
    public String index() {
        return this.PREFIX + "wechatUser.html";
    }
    
    @RequestMapping({ "/add" })
    public String wechatUserAdd(Model model) {
        List<WasteType> wasteTypeList = this.wasteTypeService.list();
        model.addAttribute("wasteTypeList",wasteTypeList);
        return this.PREFIX + "wechatUser_add.html";
    }
    
    @RequestMapping({ "/edit" })
    public String wechatUserUpdate(@RequestParam("id") final Long id,Model model) {
        List<WasteType> wasteTypeList = this.wasteTypeService.list();
        model.addAttribute("wasteTypeList",wasteTypeList);
        return this.PREFIX + "wechatUser_edit.html";
    }
    
    @RequestMapping({ "/detail/{id}" })
    @ResponseBody
    public ResponseData detail(@PathVariable final Long id) {
        final WechatUser wechatUser = (WechatUser)this.wechatUserService.getById((Serializable)id);
        WechatUserVO wechatUserVO = EntityBind.bind(wechatUser, WechatUserVO.class);
        return (ResponseData)ResponseData.success(wechatUserVO);
    }
    
    @RequestMapping({ "/list" })
    @ResponseBody
    public Object list(final WechatUser wechatUserQuery) {
        final QueryWrapper<WechatUser> wechatUserQueryWrapper = ControllerUtil.createQuery(wechatUserQuery, this.getHttpServletRequest());
        ShiroUser user = ShiroKit.getUser();
        wechatUserQueryWrapper.lambda().eq(!StrUtil.equals(user.getAccount(),"admin"),WechatUser::getUserId, user.getId());//.orderByDesc(WechatUser::getPhone);
        final Page<WechatUser> page = (Page<WechatUser>)LayuiPageFactory.defaultPage();
        final IPage<WechatUser> page2 = (IPage<WechatUser>)this.wechatUserService.page((IPage)page, (Wrapper)wechatUserQueryWrapper);
        final List<WechatUserVO> wechatUserVOList = EntityBind.bind(page2.getRecords(), WechatUserVO.class);
        final List<Map<String, Object>> list = wechatUserVOList.stream().map(wechatUser -> BeanUtil.beanToMap(wechatUser)).collect(Collectors.toList());
        page2.setRecords((List)new WechatUserWrapper(list).wrap());
        return LayuiPageFactory.createPageInfo(page2);
    }
    
    @RequestMapping({ "/addItem" })
    @ResponseBody
    public Object add(final WechatUser wechatUser) {
        ShiroUser loginUser = ShiroKit.getUser();
        wechatUser.setCreateTime(new Date());
        wechatUser.setUserNo(userNoCreator.incrementAndGet());
        wechatUser.setStatus(DictUtils.me().id("wxuser_status::common"));
        wechatUser.setWechatNickName(wechatUser.getUserName());
        wechatUser.setUserId(loginUser.getId());
        //wechatUser.setUserNo(ShiroKit.getUser().getId());
        /*String areaNext = this.getPara("areaNext");
        if(StrUtil.isNotBlank(areaNext)){
            wechatUser.setArea(wechatUser.getArea()+","+areaNext.replaceAll("[- ]",""));
        }*/
        String wasteStationId = this.getPara("wasteStationId");
        if(StrUtil.isBlank(wasteStationId)){
            return new ErrorResponseData("请选择垃圾站点");
        }
        /*if(StrUtil.isNotBlank(wechatUser.getAreaCode())){
            if (!wechatUser.getAreaCode().contains(loginUser.getAreaCode())) {
                return new ErrorResponseData("您没有添加该地区用户的权限！");
            }
            wechatUser.setArea(Utils.areaFullName(wechatUser.getAreaCode(),this.regionService));
        }*/
        this.wechatUserService.save(wechatUser);
        String typeIdsStr = this.getPara("typeIds");
        Long[] typeIds = Convert.toLongArray(typeIdsStr.split(","));
        String[] cardNos = StrUtil.split(this.getPara("cardNos"),",");

        long wasteStationIdLong = NumberUtil.parseLong(wasteStationId);
        WasteStation wasteStation = this.wasteStationService.getById(wasteStationIdLong);
        if(ObjectUtil.length(typeIds)>0){
            String typeIdStr = "";
            for(int i=0;i<typeIds.length;i++){
                Long typeId = typeIds[i];
                if(typeId==null) continue;
                if(typeIdStr.contains(typeId+"")) continue;
                typeIdStr = ","+typeId+typeIdStr;
                String cardNo = cardNos[i];
                if(typeIdStr.contains(cardNo)) continue;
                typeIdStr = ","+cardNo+typeIdStr;
                UserBin userBin = UserBin.builder().cardNo(cardNo).wasteStationId(wasteStationIdLong).wasteTypeId(typeId).userId(wechatUser.getId()).build();
                userBin.insert();
            }
        }
        if(wasteStation.getAreaCode().contains("33048310")){
            JSONObject param=new JSONObject();
            QueryWrapper<WechatUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(WechatUser::getPhone,wechatUser.getPhone()).eq(WechatUser::getAreaCode,wechatUser.getAreaCode()).eq(WechatUser::getUserNo,wechatUser.getUserNo());
            List<WechatUser> users = wechatUserService.list(queryWrapper);
            WechatUser user=users.get(0);
            switch (wasteStation.getAreaCode()){
                case "330483101206":param.put("departName","新东村");break;
                case "330483101207":param.put("departName","新妙智村");break;
                case "330483101211":param.put("departName","油车桥村");break;
                case "330483101210":param.put("departName","红旗漾村");break;
                case "330483101209":param.put("departName","新港村");break;
                case "330483101212":param.put("departName","星旗村");break;

            }

            param.put("sign","garbage_system");
            param.put("homeAddr",user.getRemark());
            param.put("isMaster",1);
            param.put("realname",user.getUserName());
            param.put("telephone",user.getPhone());
            param.put("pointCard",user.getId());
            param.put("politicalOutlook",1);
            param.put("isCivilServant",0);
            param.put("isEmptyHome",0);
            param.put("sysOrgCode",wasteStation.getZzdeptName());
            JSONObject result=aigoesRuralHomeUserThirdPush(param);

            
            if(result.get("code").equals(200) || result.get("code") == "200"){
                user.setZzid(result.get("message").toString());
                wechatUserService.updateById(user);
                System.out.println(user.getUserName()+"导入成功"+result.get("code"));
            }else{
                System.out.println(user.getUserName()+"导入失败"+result.get("code")+result.get("message"));
            }
        }

        return WechatUserController.SUCCESS_TIP;
    }

    public JSONObject aigoesRuralHomeUserThirdPush(JSONObject params){
        JSONObject jsonObject = params;
        //  int size = jsonObject.
        if(jsonObject!=null){
            jsonObject.get("id");
        }
        QueryWrapper<WechatUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.select();
        String url = "http://218.0.50.251:80/garbage/api/zhenCang/aigoesRuralHomeUserThirdPush";
        JSONObject result = Utils.doPost(url,params);
        return result;

    }

    @RequestMapping({ "/delete" })
    @ResponseBody
    public Object delete(@RequestParam final Long id) {
        int count = this.orderFormService.count(new QueryWrapper<OrderForm>().lambda().eq(OrderForm::getUserId, id));
        if(count>0){
            return new ErrorResponseData("删除失败，该用户已参与过回收，有回收记录！");
        }
        this.wechatUserService.removeById((Serializable)id);
        return WechatUserController.SUCCESS_TIP;
    }
    
    @RequestMapping({ "/editItem" })
    @ResponseBody
    public Object update(final WechatUser wechatUser) {
        String wasteStationId = this.getPara("wasteStationId");
        if(StrUtil.isBlank(wasteStationId)){
            return new ErrorResponseData("请选择垃圾站点");
        }
        if(StrUtil.isNotBlank(wechatUser.getAreaCode())){
            wechatUser.setArea(Utils.areaFullName(wechatUser.getAreaCode(),this.regionService));
        }
        this.wechatUserService.updateById(wechatUser);
        QueryWrapper<UserBin> userBinQueryWrapper = new QueryWrapper<>();
        userBinQueryWrapper.lambda().eq(UserBin::getUserId,wechatUser.getId());
        this.userBinService.remove(userBinQueryWrapper);

        String typeIdsStr = this.getPara("typeIds");
        Long[] typeIds = Convert.toLongArray(typeIdsStr.split(","));
        String[] cardNos = StrUtil.split(this.getPara("cardNos"),",");
        if(ObjectUtil.length(typeIds)>0){
            String typeIdStr = "";
            long wasteStationIdLong = NumberUtil.parseLong(wasteStationId);
            for(int i=0;i<typeIds.length;i++){
                Long typeId = typeIds[i];
                if(typeId==null) continue;
                if(typeIdStr.contains(typeId+"")) continue;
                typeIdStr = ","+typeId+typeIdStr;
                String cardNo = cardNos[i];
                if(typeIdStr.contains(cardNo)) continue;
                typeIdStr = ","+cardNo+typeIdStr;
                UserBin userBin = UserBin.builder().cardNo(cardNo).wasteStationId(wasteStationIdLong).wasteTypeId(typeId).userId(wechatUser.getId()).build();
                userBin.insert();
            }
        }
        return WechatUserController.SUCCESS_TIP;
    }
    
    @RequestMapping(value = { "/delItems" }, method = { RequestMethod.POST })
    @ResponseBody
    public Object delItem(@RequestBody final Long[] ids) {
        this.wechatUserService.removeByIds((Collection)Arrays.asList(ids));
        return WechatUserController.SUCCESS_TIP;
    }
    
    @RequestMapping({ "/show" })
    public Object show(final Long id, final Model model) {
        final WechatUser wechatUser = (WechatUser)this.wechatUserService.getById((Serializable)id);
        final Map map = BeanUtil.beanToMap(wechatUser);
        model.addAttribute("wechatUser", new WechatUserWrapper(map).wrap());
        return this.PREFIX + "wechatUser_show.html";
    }
    
    @RequestMapping({ "/regByUserInfo" })
    @ResponseBody
    public Object regByUserInfo(@RequestBody final Map<String, String> userData) {
        final String appId = MapUtil.getStr((Map)userData, "appId");
        final WxMaService wxService = WxMaConfiguration.getMaService(appId);
        final String code = MapUtil.getStr((Map)userData, "code");
        try {
            final WxMaUserService userService = wxService.getUserService();
            final WxMaJscode2SessionResult session = userService.getSessionInfo(code);
            final String openid = session.getOpenid();
            final String encryptedData = userData.get("encryptedData");
            final String ivStr = userData.get("iv");
            final WxMaUserInfo userInfo = userService.getUserInfo(session.getSessionKey(), encryptedData, ivStr);
            WechatUser existUser = this.wechatUserService.findByOpenId(openid);
            if (existUser == null) {
                final String mpCode = WxUtils.maConfig.get(appId);
                final WechatUser build = WechatUser.builder().openId(openid).avatarUrl(userInfo.getAvatarUrl()).wechatNickName(userInfo.getNickName()).mpCode(mpCode).build();
                existUser = this.wechatUserService.getByOpenId(build);
            }
            else {
                existUser.setAvatarUrl(userInfo.getAvatarUrl());
                existUser.setWechatNickName(userInfo.getNickName());
                existUser.updateById();
            }
            if (!StringUtils.isBlank((CharSequence)existUser.getPhone())) {
                final Map<String, Object> token = this.createToken(openid, existUser.getPhone(), appId);
                return new SuccessResponseData(token);
            }
            return new ErrorResponseData(Integer.valueOf(201), "\u6ca1\u6709\u624b\u673a\u53f7");
        }
        catch (WxErrorException e) {
            e.printStackTrace();
            return new ErrorResponseData("\u6ce8\u518c\u5931\u8d25");
        }
    }
    
    @RequestMapping({ "/wxlogin" })
    @ResponseBody
    public Object login(@RequestBody final Map<String, String> userData) {
        final String phoneNumber1 = userData.get("phoneNumber");
        if (!StringUtils.isBlank((CharSequence)phoneNumber1)) {
            final QueryWrapper<WechatUser> wechatUserQueryWrapper = (QueryWrapper<WechatUser>)new QueryWrapper();
            wechatUserQueryWrapper.lambda().eq(WechatUser::getPhone, phoneNumber1);
            final WechatUser phoneUser = (WechatUser)this.wechatUserService.getOne((Wrapper)wechatUserQueryWrapper, false);
            if (phoneUser == null) {
                return new ErrorResponseData("\u8be5\u624b\u673a\u53f7\u5c1a\u672a\u6ce8\u518c,\u8bf7\u4f7f\u7528\u4e00\u952e\u767b\u5f55!");
            }
            final String mpCode = phoneUser.getMpCode();
            final String appId = WxUtils.wechatAppConfig.get(mpCode);
            final Map<String, Object> resultMap = this.createToken(phoneUser.getOpenId(), phoneNumber1, appId);
            return new SuccessResponseData(resultMap);
        }
        else {
            final String appId2 = MapUtil.getStr((Map)userData, "appId");
            final WxMaService wxService = WxMaConfiguration.getMaService(appId2);
            final String code = MapUtil.getStr((Map)userData, "code");
            try {
                final WxMaUserService userService = wxService.getUserService();
                final WxMaJscode2SessionResult session = userService.getSessionInfo(code);
                final String openid = session.getOpenid();
                final String encryptedData = userData.get("encryptedData");
                final String ivStr = userData.get("iv");
                final WxMaPhoneNumberInfo phoneNoInfo = userService.getPhoneNoInfo(session.getSessionKey(), encryptedData, ivStr);
                final String phoneNumber2 = phoneNoInfo.getPhoneNumber();
                final WechatUser byOpenId = this.wechatUserService.findByOpenId(openid);
                if (byOpenId == null) {
                    final WxMaUserInfo userInfo = userService.getUserInfo(session.getSessionKey(), encryptedData, ivStr);
                    final WechatUser build = WechatUser.builder().openId(openid).phone(phoneNumber2).avatarUrl(userInfo.getAvatarUrl()).wechatNickName(userInfo.getNickName()).mpCode((String)WxUtils.maConfig.get(appId2)).build();
                    this.wechatUserService.getByOpenId(build);
                }
                else if (StringUtils.isBlank((CharSequence)byOpenId.getPhone())) {
                    byOpenId.setPhone(phoneNumber2);
                    byOpenId.updateById();
                }
                final Map<String, Object> resultMap2 = this.createToken(openid, phoneNumber2, appId2);
                return new SuccessResponseData(resultMap2);
            }
            catch (WxErrorException e) {
                e.printStackTrace();
                return new ErrorResponseData("");
            }
        }
    }
    
    private Map<String, Object> createToken(final String openid, final String phoneNumber, final String appId) {
        final DateTime now = new DateTime();
        final DateTime nowPlus7 = now.offsetNew(DateField.DAY_OF_MONTH, 7);
        final WechatUser user = this.wechatUserService.findByOpenId(openid);
        final WxLogin wxLogin = WxLogin.builder().loginTime(now.toJdkDate()).expireTime((Date)nowPlus7).openId(openid).phoneNo(phoneNumber).appId(appId).nickName(user.getWechatNickName()).avatarUrl(user.getAvatarUrl()).userNo(user.getUserNo()).build();
        final String token = IdUtil.fastSimpleUUID();
        Const.tokenMap.put(token, wxLogin);
        final Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("token", token);
        resultMap.put("expireTime", nowPlus7.getTime());
        resultMap.put("userName", wxLogin.getNickName());
        resultMap.put("userNo", wxLogin.getUserNo());
        resultMap.put("avatarUrl", wxLogin.getAvatarUrl());
        return resultMap;
    }
    
    @RequestMapping({ "createMyQrcode" })
    @ResponseBody
    public Object myQrcode(final String token) {
        final WxLogin wxLogin = Const.tokenMap.get(token);
        final WechatUser user = this.wechatUserService.getByOpenId(wxLogin.getOpenId());
        final String qrcodeImgPath = user.getQrcodeImgPath();
        final String qrcodePath = ControllerUtil.getRealPath("/upload/qrcode");
        final File file = new File(qrcodePath, qrcodeImgPath);
        if (file.exists()) {
            return new SuccessResponseData(("/upload/qrcode" + user.getId() + ".png"));
        }
        final String appId = wxLogin.getAppId();
        final WxMaService wxService = WxMaConfiguration.getMaService(appId);
        try {
            final File wxaCodeUnlimit = wxService.getQrcodeService().createWxaCodeUnlimit(user.getId() + "", "pages/index/index");
            final File destFile = new File(qrcodeImgPath, user.getId() + ".png");
            FileUtils.copyFile(wxaCodeUnlimit, destFile);
            user.setQrcodeImgPath(user.getId() + ".png");
            user.updateById();
            return new SuccessResponseData(("/upload/qrcode" + user.getId() + ".png"));
        }
        catch (WxErrorException e) {
            e.printStackTrace();
        }
        catch (IOException e2) {
            e2.printStackTrace();
        }
        return new ErrorResponseData("\u4e8c\u7ef4\u7801\u83b7\u53d6\u5931\u8d25!");
    }
    
    @RequestMapping({ "/createUserRelative" })
    @ResponseBody
    public Object createUserRelative(final String code, final String wxAppId, final String miniProgramAppId) {
        final WxMaService wxService = WxMaConfiguration.getMaService(miniProgramAppId);
        WxMaJscode2SessionResult session = null;
        try {
            session = wxService.getUserService().getSessionInfo(code);
            final String openid = session.getOpenid();
            final WechatUser miniAppUser = this.wechatUserService.getByOpenId(openid);
            final WechatUser wxAppUser = this.wechatUserService.getByOpenId(wxAppId);
            if (StringUtils.isBlank((CharSequence)wxAppUser.getMiniProgramId())) {
                wxAppUser.setMiniProgramId(miniProgramAppId);
                wxAppUser.updateById();
            }
            if (StringUtils.isBlank((CharSequence)miniAppUser.getMiniProgramId())) {
                miniAppUser.setMiniProgramId(wxAppId);
                miniAppUser.updateById();
            }
        }
        catch (WxErrorException e) {
            e.printStackTrace();
            return new ErrorResponseData("");
        }
        return new SuccessResponseData();
    }
    
    @RequestMapping({ "/qrcode/{appid}/{maCode}" })
    public Object qrcode(@PathVariable("appid") final String appid, @PathVariable("maCode") final String maCode, final String code, final Model model) {
        final boolean switchover = this.wxService.switchover(appid);
        if (switchover) {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
            try {
                wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
                final String mpOpenId = wxMpOAuth2AccessToken.getOpenId();
                final WechatUser mpUser = this.wechatUserService.getByOpenId(mpOpenId);
                File qrcodeSaveFile = null;
                String qrcodeImgPath = mpUser.getQrcodeImgPath();
                final String qrcodeRootPath = ToolUtil.getWebRootPath("/upload/qrcode");
                if (StringUtils.isNotBlank((CharSequence)qrcodeImgPath)) {
                    qrcodeSaveFile = new File(qrcodeRootPath, qrcodeImgPath);
                    if (!qrcodeSaveFile.exists()) {
                        qrcodeImgPath = null;
                    }
                }
                if (StringUtils.isBlank((CharSequence)qrcodeImgPath)) {
                    if (StringUtils.isBlank((CharSequence)mpUser.getQrcodeUrl())) {
                        final WxMpQrCodeTicket wxMpQrCodeTicket = this.wxService.getQrcodeService().qrCodeCreateLastTicket(mpUser.getId().toString());
                        mpUser.setQrcodeCreateTime(new Date());
                        mpUser.setQrcodeTicket(wxMpQrCodeTicket.getTicket());
                        mpUser.setQrcodeUrl(wxMpQrCodeTicket.getUrl());
                    }
                    qrcodeImgPath = this.createQrcode(mpUser.getQrcodeUrl());
                    mpUser.setQrcodeImgPath(qrcodeImgPath);
                    mpUser.insertOrUpdate();
                }
                qrcodeSaveFile = new File(qrcodeRootPath, qrcodeImgPath);
                final WxMediaUploadResult res = this.wxService.getMaterialService().mediaUpload("image", qrcodeSaveFile);
                model.addAttribute("qrcodePath", qrcodeImgPath);
                String maOpenIdByCode = "";
                final String maAppId = WxUtils.getDefaultMa();
                final WxMaService wxService = WxMaConfiguration.getMaService(maAppId);
                final WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(maCode);
                maOpenIdByCode = session.getOpenid();
                final WechatUser maUser = this.wechatUserService.getByOpenId(maOpenIdByCode);
                final String userMaOpenId = mpUser.getMiniProgramId();
                if (StringUtils.isBlank((CharSequence)userMaOpenId)) {
                    mpUser.setMiniProgramId(maOpenIdByCode);
                    mpUser.setWechatNickName(maUser.getWechatNickName());
                    mpUser.setAvatarUrl(maUser.getAvatarUrl());
                    mpUser.setPhone(maUser.getPhone());
                    mpUser.updateById();
                }
                final String miniProgramId = maUser.getMiniProgramId();
                if (StringUtils.isBlank((CharSequence)miniProgramId)) {
                    maUser.setMiniProgramId(mpOpenId);
                    maUser.updateById();
                }
                final QueryWrapper<WechatUser> wechatUserQueryWrapper = (QueryWrapper<WechatUser>)new QueryWrapper();
                wechatUserQueryWrapper.lambda().eq(WechatUser::getUserId, mpUser.getId());
                final int count = this.wechatUserService.count((Wrapper)wechatUserQueryWrapper);
                model.addAttribute("count", count);
                model.addAttribute("user", mpUser);
            }
            catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        return this.PREFIX + "qrcode.html";
    }
    
    @RequestMapping({ "/show_qrcode" })
    public Object showQrcode(final Long id, final Model model) {
        final WechatUser user = (WechatUser)this.wechatUserService.getById((Serializable)id);
        final String qrcodeImgPath = this.createQrcode(user.getQrcodeUrl());
        final String webPath = ToolUtil.getWebRootPath("/upload/qrcode");
        final String classPath = ControllerUtil.getRealPath("/upload/qrcode");
        if (!StringUtils.equals((CharSequence)webPath, (CharSequence)classPath)) {
            try {
                FileUtils.copyFile(new File(webPath, qrcodeImgPath), new File(classPath, qrcodeImgPath));
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        final QueryWrapper<WechatUser> wechatUserQueryWrapper = (QueryWrapper<WechatUser>)new QueryWrapper();
        wechatUserQueryWrapper.lambda().eq(WechatUser::getUserId, user.getId());
        final int count = this.wechatUserService.count((Wrapper)wechatUserQueryWrapper);
        model.addAttribute("count", count);
        model.addAttribute("user", user);
        model.addAttribute("qrcodePath", qrcodeImgPath);
        return this.PREFIX + "qrcode.html";
    }
    
    private String createQrcode(final String qrcodeContent) {
        final byte[] qrcode = QrcodeUtils.createQrcode(qrcodeContent, 342, (File)null);
        final File qrcodeSaveFile = new File(ToolUtil.getWebRootPath("/upload/qrcode"), UUID.randomUUID().toString() + ".jpg");
        try {
            IOUtils.write(qrcode, (OutputStream)new FileOutputStream(qrcodeSaveFile));
            final File qrcodeBgFile = new File(ToolUtil.getWebRootPath("/upload/qrcode"), "qrcode_gb.jpg");
            System.out.println(qrcodeBgFile.getAbsolutePath());
            final BufferedImage qrcodeBgImg = ImageIO.read(qrcodeBgFile);
            final BufferedImage qrcodeImg = ImageIO.read(qrcodeSaveFile);
            final int w = qrcodeImg.getWidth();
            final int h = qrcodeImg.getHeight();
            final Graphics2D g = qrcodeBgImg.createGraphics();
            g.drawImage(qrcodeImg, 189, 598, w, h, null);
            g.dispose();
            ImageIO.write(qrcodeBgImg, "jpg", qrcodeSaveFile);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return qrcodeSaveFile.getName();
    }
    

    
    @RequestMapping({ "/checkReg" })
    @ResponseBody
    public Object checkReg(final String appId, final String code) {
        try {
            final WxMaService wxService = WxMaConfiguration.getMaService(appId);
            final WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            final String mpOpenId = session.getOpenid();
            final WechatUser user = this.wechatUserService.findByOpenId(mpOpenId);
            if (user == null) {
                return new ErrorResponseData(Integer.valueOf(400), "\u5c1a\u672a\u6ce8\u518c");
            }
            int errorCode = 200;
            if (StringUtils.isAnyBlank(new CharSequence[] { user.getWechatNickName(), user.getAvatarUrl() })) {
                ++errorCode;
            }
            if (StringUtils.isBlank((CharSequence)user.getPhone())) {
                errorCode += 10;
            }
            if (errorCode == 200) {
                final Map<String, Object> loginInfoMap = this.createToken(mpOpenId, user.getPhone(), appId);
                return new SuccessResponseData(loginInfoMap);
            }
            return new ErrorResponseData(Integer.valueOf(errorCode), "\u5df2\u6ce8\u518c,\u4f46\u4fe1\u606f\u4e0d\u5b8c\u6574!");
        }
        catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData(Integer.valueOf(400), "\u5c1a\u672a\u6ce8\u518c");
        }
    }
    
    @RequestMapping({ "/createUserNo" })
    @ResponseBody
    public Object createUserNo() {
        final QueryWrapper<WechatUser> wechatUserQueryWrapper = (QueryWrapper<WechatUser>)new QueryWrapper();
        wechatUserQueryWrapper.lambda().isNull(WechatUser::getUserNo);
        final List<WechatUser> list = (List<WechatUser>)this.wechatUserService.list((Wrapper)wechatUserQueryWrapper);
        list.stream().forEach(user -> {
            user.setUserNo(this.userNoCreator.incrementAndGet());
            user.updateById();
            return;
        });
        return new SuccessResponseData();
    }

    @RequestMapping("/goImport")
    public Object goImport(){
        String pageUrl = this.PREFIX + "qrcode.html";
        System.out.println("跳转："+pageUrl);
        return pageUrl;
    }
    @RequestMapping("/import")
    @ResponseBody
    public Object importData(Model model){
        final HttpServletRequest request = this.getHttpServletRequest();
        final String header = request.getHeader("content-type");
        if (StringUtils.containsIgnoreCase((CharSequence)header, (CharSequence)"multipart/form-data")) {
            final StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
            final MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            final Map<String, MultipartFile> fileMap = (Map<String, MultipartFile>)multipartRequest.getFileMap();
            final boolean file1 = fileMap.containsKey("file");
            if (file1) {
                final MultipartFile file2 = multipartRequest.getFile("file");
                try {
                    if (file2.getSize()>0) {
                        ExcelReader reader = ExcelUtil.getReader(file2.getInputStream());
                        /*final String name = file2.getOriginalFilename();
                        final InputStream inputStream = file2.getInputStream();
                        String fileName = ControllerUtil.saveFile("/upload/img", inputStream, name);
                        SuccessResponseData successResponseData = new SuccessResponseData();
                        successResponseData.setMessage("上传成功，文件名为："+fileName);
                        model.addAttribute("response", successResponseData);*/
                        Map<String, Dict> sex = DictUtils.me().getByType("SEX");

                        List<WasteType> list = this.wasteTypeService.list();
                        Map<String, Long> wasteTypeMap = list.stream().collect(Collectors.toMap(WasteType::getTypeName, WasteType::getId));

                        List<Map<String, Object>> maps = reader.readAll();
                        List<WechatUser> userList = new ArrayList<>();
                        List<UserBin> userBins = new ArrayList<>();
                        for (Map<String, Object> map : maps) {
                            WechatUser user = new WechatUser();

                            String name = MapUtil.getStr(map, "姓名");
                            user.setUserName(name);

                            String address = MapUtil.getStr(map, "住址");
                            user.setRemark(address);

                            String sexStr = MapUtil.getStr(map, "性别");
                            Dict dict = StrUtil.equals(sexStr, "男") ? sex.get("M") : sex.get("F");
                            if(dict!=null)
                            user.setSex(dict.getDictId());

                            String birthday = MapUtil.getStr(map, "出生日期");
                            Date birthdayDate = Convert.toDate(birthday);
                            user.setBirthDay(birthdayDate);

                            String phone = MapUtil.getStr(map, "手机号");
                            user.setPhone(phone);

                            String email = MapUtil.getStr(map, "电子邮箱");
                            user.setEmail(email);


                            user.setCreateTime(new Date());
                            user.setUserNo(userNoCreator.incrementAndGet());
                            this.wechatUserService.save(user);

                            Long userId = user.getId();

                            String cardType1 = MapUtil.getStr(map,"垃圾桶类别1");
                            Long cardTypeId1 = wasteTypeMap.get(cardType1);

                            String cardNo1 = MapUtil.getStr(map,"卡号1");
                            if(cardTypeId1!=null && StrUtil.isNotBlank(cardNo1)){
                                UserBin userBin = UserBin.builder().userId(userId).cardNo(cardNo1).wasteTypeId(cardTypeId1).build();
                                userBins.add(userBin);
                            }


                            String cardType2 = MapUtil.getStr(map,"垃圾桶类别2");
                            Long cardTypeId2 = wasteTypeMap.get(cardType2);
                            String cardNo2 = MapUtil.getStr(map,"卡号2");

                            if(cardTypeId2!=null && StrUtil.isNotBlank(cardNo2)){
                                UserBin userBin = UserBin.builder().userId(userId).cardNo(cardNo2).wasteTypeId(cardTypeId2).build();
                                userBins.add(userBin);
                            }

                            userList.add(user);
                        }
                        if(userBins.size()>0){
                            this.userBinService.saveBatch(userBins);
                        }
                    }else{
                        model.addAttribute("response",new ErrorResponseData("请选择需要上传的图片或视屏。"));
                    }

                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }

    @RequestMapping("/showExchange")
    public Object showExchange(Long id,Model model){
        WechatUser user = this.wechatUserService.getById(id);
        Double withdraw = user.getWithdraw();
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.lambda().le(Product::getJifen,withdraw).eq(Product::getStatus,DictUtils.me().getId("product_status::add"));
        List<Product> productList = this.productService.list(productQueryWrapper);
        model.addAttribute("productList",productList);
        model.addAttribute("user",user);
        return PREFIX+"/showExchange.html";
    }

    @Autowired
    private ProductExchangeService productExchangeService;

    @RequestMapping("/exchangeProduct")
    @ResponseBody
    public Object exchangeProduct(Long userId,Long productId){
        Product product = this.productService.getById(productId);
        if(product==null){
            return new ErrorResponseData("商品不存在或已下架！");
        }
        WechatUser user = this.wechatUserService.getById(userId);
        if(user==null){
            return new ErrorResponseData("指定用户不存在!");
        }
        Double withdraw = ObjectUtil.defaultIfNull(user.getWithdraw(),0.0);
        if(withdraw.compareTo(product.getJifen())>=0) {
            ProductExchange productExchange = ProductExchange.builder().createTime(new Date()).productJifen(product.getJifen()).useJifen(product.getJifen()).productId(productId).userId(ShiroKit.getUser().getId()).wechatId(userId).build();
            this.productExchangeService.save(productExchange);
            UpdateWrapper<WechatUser> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.lambda().setSql("withdraw=withdraw-"+product.getJifen()).eq(WechatUser::getId,user.getId());
            this.wechatUserService.update(userUpdateWrapper);
            return new SuccessResponseData();
        }else{
            return new ErrorResponseData("积分不足！");
        }

    }
}
